package agitext

import (
	"encoding/base64"
	"encoding/json"
	"os"
	"time"
)

const _AGitSpaceXParamsEnvKey = "SPACEX_PAYLOAD"

type SpaceXParams struct {
	Enabled          bool      `json:"enabled"`
	Operation        string    `json:"operation"`
	ConnType         string    `json:"conn_type"`
	Time             time.Time `json:"-"`
	SpaceXHost       string    `json:"spacex_host"`
	SpaceXPort       int64     `json:"spacex_port"`
	TransactionID    uint64    `json:"transaction_id"`
	TransactionVoter string    `json:"transaction_voter"`
	MainHooker       bool      `json:"main_hooker"`
	Addrs            []string  `json:"addrs"`
}

// GetSpaceXParamsFromEnv extracts space params from environment variables
func GetSpaceXParamsFromEnv() (*SpaceXParams, error) {
	res := &SpaceXParams{}
	payload := os.Getenv(_AGitSpaceXParamsEnvKey)
	if payload == "" {
		return res, nil
	}

	raw, err := base64.StdEncoding.DecodeString(payload)
	if err != nil {
		return nil, err
	}

	if err := json.Unmarshal(raw, res); err != nil {
		return nil, err
	}

	return res, nil
}
